昨天提到reduce
那今天就來說說reduce的另一個兄弟 reduceRight吧
array.reduceRight() 跟reduce 的功能大同小異
差別在於, reduceRight 是由右至左
開始做累加
reduceRight一樣會回傳四個參數
array.reduceRight(function(accumulator , currentValue, currentIndex, arr),initialValue)
initialValue - 累加的初始值
程式碼如下:
let sum = [0, 11, 12, 23, 14, 15].reduceRight(function (
acc,
currentValue,
index,
arr
) {
return acc + currentValue;
},
10); //初始值使用10
console.log(sum); //10+15+14+23+12+11=85
No | acc | currentValue | index | arr |
---|---|---|---|---|
1 | 10 | 15 | 5 | [0,11,12,23,14,25] |
2 | 25 | 14 | 4 | [0,11,12,23,14,25] |
3 | 39 | 23 | 3 | [0,11,12,23,14,25] |
4 | 62 | 12 | 2 | [0,11,12,23,14,25] |
5 | 74 | 11 | 1 | [0,11,12,23,14,25] |
6 | 85 | 0 | 0 | [0,11,12,23,14,25] |
參考來源:
https://www.fooish.com/javascript/array/reduceRight.html